package com.example.nutritionmanager.viewModels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.nutritionmanager.ai.Message
import com.example.nutritionmanager.conversationApi.SSEClient
import com.example.nutritionmanager.data.ChatDataStore
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

// ViewModel处理逻辑
@HiltViewModel
class AIChatViewModel @Inject constructor(
    private val chatDataStore: ChatDataStore
) : ViewModel() {
    val sseClient =  SSEClient() // 初始化SSEClient

    private val _messages = MutableStateFlow<List<Message>>(emptyList())
    val messages: StateFlow<List<Message>> = _messages.asStateFlow()

    // 当前正在处理的AI消息索引
    private var pendingAIMessageIndex = -1

    init {
        loadHistory()
    }

    private fun loadHistory() {
        viewModelScope.launch {
            chatDataStore.chatHistory.collect { history ->
                _messages.value = history
            }
        }
    }

    private fun addMessage(message: Message) {
        _messages.update { it + message }
    }

    private fun appendToLastAIMessage(text: String) {
        _messages.update { currentMessages ->
            currentMessages.toMutableList().apply {
                if (pendingAIMessageIndex in indices) {
                    this[pendingAIMessageIndex] = this[pendingAIMessageIndex].copy(
                        text = this[pendingAIMessageIndex].text + text
                    )
                }
            }
        }
    }
    fun sendMessage(messageToSend: String) {
        viewModelScope.launch {
            // 添加用户消息
            addMessage(Message(messageToSend, isUser = true))

            // 添加初始AI消息占位
            addMessage(Message("", isUser = false))
            pendingAIMessageIndex = _messages.value.lastIndex

            // 保存到DataStore
            chatDataStore.saveChat(_messages.value)

            // 启动SSE请求（使用协程安全回调）
            sseClient.startSSERequest(messageToSend, object : SSEClient.MessageListener {
                override fun onAppendMessage(text: String) {
                    viewModelScope.launch {  // 添加协程作用域
                        appendToLastAIMessage(text)
                    }
                }

                override fun onFinish() {
                    viewModelScope.launch {  // 添加协程作用域
                        pendingAIMessageIndex = -1
                        chatDataStore.saveChat(_messages.value)
                    }
                }
            })
        }
    }
}